#pragma once

#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "log.hpp"
#include "Comm.hpp"
#include"InetAddr.hpp"
using namespace std;
const uint16_t defoultport = 8888;
const static int defaultfd = -1;
const int defaultsize = 1024;
class Udpserver : public nocopy
{
public:
     Udpserver(/*const std::string &ip*/ const uint16_t port = defoultport)
        : _port(port)
    {
    }
    void Init()
    {
        // 1. 创建socket，就是创建了文件细节
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg.massage(Fatal, "socket errr,%d:%s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.massage(Info, "socket success, sockfd: %d\n", _sockfd);
       // 2. 绑定，指定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = 0;
        //  local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        // 结构体填完，设置到内核中了吗？？没有
        if (n != 0)
        {
            lg.massage(Fatal, "bind_rr %d:%s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
    }
    void Start()
    {
        char buffer[defaultsize];
        // 服务器永远不退出
        for (;;)
        {

            struct sockaddr_in peer;
            
            socklen_t len = sizeof(peer);//不能乱写
            
            //ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                buffer[n] = 0;
                 std::cout << "[" << addr.PrintDebug() << "]# " << buffer << std::endl;
                std::cout << "client sar#" << buffer << std::endl;
                
                sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~Udpserver()
    {
    }

private:
     //std::string _ip;
    uint16_t _port;
    int _sockfd;
};